/**
 * weapp-js v1.7.1(2021-4-16)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2021 Motigo, Inc.
 * 
 */
import urllib from "./utils/url.js";
export default {
    _loaded: {},
    /** load: 预加载
     * 
     * @param {string|array} urls 
     * @param {object} opts 
       {
           success: res=>{  // 成功回调：全部都预加载成功才算成功
           },
           fail: res=>{  // 失败回调：只要有一个失败就算失败
           },
           complete: res=>{ // 完成回调：success和fail后都会调用
                res.successed;  // 成功的url列表
                res.failed;     // 失败的url列表 {url:'', err: ''}
           },
           progress: res=>{  // 进度回调
                res.url;     // 当前完成的url
                res.current; // 当前完成个数
                res.total;   // 总个数
           }
       }
     */
    load(urls, opts) {
        opts = opts || {};

        if(urls instanceof Array) {
            this._loadUrls(urls, opts);
        } else if (typeof(urls) == 'string') {
            this._loadUrls([urls], opts);
        } else {
            const res = {
                url: urls,
                err: 'invalid urls'
            };

            opts.fail && opts.fail(res);
            opts.complete && opts.complete(res);
        }
    },
    /** getPath: 获取路径
     *  如果有预加载，则返回预加载后的本地临时路径；如果未预加载，则返回传入参数url
     * @param {string} url 
     */
    getPath(url) {
        if(url in this._loaded && this._loaded[url] && typeof this._loaded[url] == "string" && this._loaded[url].length > 0) {
            return this._loaded[url];
        } else {
            return url;
        }
    },
    // 缓存的key
    _cacheKey(url) {
        return '[PRELOAD]' + url;
    },
    // 记录预加载信息
    _record(url, tempFilePath, useCache) {
        if(url && tempFilePath) {
            this._loaded[url] = tempFilePath;
            if(!useCache) { // 已经使用cache，不更新storage
                wx.setStorage({
                    key: this._cacheKey(url),
                    data: JSON.stringify({
                        create_time: parseInt(Date.now()/1000.0),
                        file_path: tempFilePath
                    })
                });
            }
        }
    },
    // 预加载url列表
    _loadUrls(urls, opts) {
        const count = urls.length;
        const successed = [];
        const failed = [];

        urls.forEach(url => {
            this._downloadFile({
                url: url,
                timeout: opts.timeout || 10*1000,
                success: res => {
                    if (res.statusCode === 200 || res.statusCode === 304) {
                        this._record(url, res.tempFilePath, res.statusCode === 304);
                        successed.push(url);

                        if(res.statusCode === 200) {
                            console.log('wx download success:', url);
                        }
                    } else {
                        failed.push({
                            url: url,
                            err: 'invalid server statuc code:' + res.statusCode
                        });
                    }
                },
                fail: err=>{
                    console.log('download fail:', err, url);
                    failed.push({
                        url: url,
                        err: err.errMsg
                    });
                },
                complete: ()=>{
                    const handled = successed.length + failed.length;
                    opts.progress && opts.progress({
                        url: url,
                        current: handled,
                        total: count
                    })

                    if(handled === count) {
                        if (failed.length === 0) {
                            opts.success && opts.success({
                                urls: urls
                            })
                        } else {
                            opts.fail && opts.fail({
                                urls: urls,
                                successed: successed,
                                failed: failed
                            })
                        }

                        opts.complete && opts.complete({
                            urls: urls,
                            successed: successed,
                            failed: failed
                        })
                    }
                }
            })
        });
    },
    // 下载文件封装：会先检测本地缓存，没缓存或缓存失效才真正下载
    _downloadFile(opts) {
        // 检查url合法性
        if(!( opts && opts.url && typeof opts.url == "string" && opts.url.length > 0 && urllib.isValidUrl(opts.url))){
            // url 不合法
            opts && opts.fail && opts.fail({
                "errMsg":"invalid url"
            })
            opts && opts.complete && opts.complete()
            return
        }
        const key = this._cacheKey(opts.url);
        let temp_path = null;
        var cache_data = wx.getStorageSync(key);
        if(cache_data) {
            try {
                const data = JSON.parse(cache_data);

                temp_path = data.file_path;
            } catch (e) {
                temp_path = null;
            }
        }

        if (temp_path) {
            wx.getFileInfo({
                filePath: temp_path,
                success: res=>{                    
                    if (res.size>0) {
                        console.log('use cached preload file');
                        opts.success && opts.success({
                            statusCode: 304,
                            tempFilePath: temp_path
                        });
                        opts.complete && opts.complete();
                    } else {
                        wx.downloadFile(opts);
                    }
                },
                fail: err=>{
                    console.log('file info fail:', err);
                    wx.downloadFile(opts);
                }
            })
        } else {
            wx.downloadFile(opts);
        }
    }
}
